import yaml
import template
import uix
import util
import xtriui
import uiutil
import uicls

class AttrsFromDict():

    def __init__(self, dict):
        self.__dict__.update(dict)



    def __getattr__(self, name):
        return getattr(self.__dict__, name)



    def UpdatedFromYaml(self, yamlStr):
        d = self.__dict__.copy()
        d.update(yaml.load(yamlStr))
        return AttrsFromDict(d)




def MakeFromYaml(yamlStr, ignoreMocks = True):
    try:
        return _MakeRootFromWinDict(yaml.load(yamlStr), ignoreMocks=ignoreMocks)
    except:
        print 'Offending YAML is:'
        print yamlStr
        raise 



def CopyFromYaml(original, yamlStr, ignoreMocks = True):
    d = yaml.load(yamlStr)
    tmp = _MakeRootFromWinDict(d, ignoreMocks=ignoreMocks)
    for k in d:
        if (k in ('type', 'mock', 'id', 'children')):
            continue
        if hasattr(tmp, k):
            setattr(original, k, getattr(tmp, k))

    for child in tmp.children[:]:
        uiutil.Transplant(child, original)

    if hasattr(tmp, 'sr'):
        GetSrDict(original).update(GetSrDict(tmp))
    tmp.Close()



def GetSrDict(wnd):
    import uiutil
    if isinstance(wnd.sr, uiutil.Bunch):
        return wnd.sr
    else:
        return wnd.sr.__dict__



def _MakeRootFromWinDict(d, ignoreMocks = True):
    ids = {}
    ret = _MakeFromWinDict(d, ids=ids, ignoreMocks=ignoreMocks)
    if (ids and (not hasattr(ret, 'sr'))):
        ret = uicls.Container(ret)
    if ids:
        GetSrDict(ret).update(ids)
    return ret



def _MakeFromWinDict(d, ids, ignoreMocks = True):
    d = AttrsFromDict(d)
    maker = getattr(template, ('Make_%s' % d.type))
    ret = maker(d, ids=ids, ignoreMocks=ignoreMocks)
    AssignID(ret, d, ids)
    ret.name = Name(d)
    return ret



def MakeChildren(parent, lst, ids, ignoreMocks):
    parent.children.extend([ _MakeFromWinDict(windict, ids=ids, ignoreMocks=ignoreMocks) for windict in lst if not((ignoreMocks and windict.get('mock', False))) ])



def AlignFromStr(s):
    if (s == 'fill'):
        s = 'client'
    return getattr(uix, ('UI_AL%s' % s.upper()))



def StateFromStr(s):
    return getattr(uix, ('UI_%s' % s.upper()))



def PositionFromStr(s):
    if (s == 'default'):
        s = 'none'
    return getattr(uix, ('AUTOPOS%s' % s.upper()))



def AnchorsFromStr(s):
    return sum([ getattr(uix, ('UI_ANCH%s' % s.upper())) for s in map(str.strip, s.split(',')) ])



def Color(s):
    if isinstance(s, list):
        return tuple(s)
    else:
        return {'red': (1.0, 0.0, 0.0, 0.25),
         'green': (0.0, 1.0, 0.0, 0.25)}.get(s, tuple(s))



def Name(d):
    return d.get('name', d.get('id', d.type))



def AssignID(window, d, ids):
    if ('id' in d):
        if (d.id in ids):
            raise RuntimeError(("Repeated id '%s' ." % d.id))
        ids[d.id] = window


exports = util.AutoExports('template', locals())

